<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
  <title>发布红包</title>
  <link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"
  />
  <link rel="stylesheet" href="css/app.v2.css" type="text/css"
  />
  <style type="text/css">
    #panel {
      position: absolute;
      background-color: white;
      max-height: 90%;
      overflow-y: auto;
      top: 10px;
      right: 10px;
      width: 280px;
    }
  </style>
  <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.2&key=375baa190cd4cf5709afb11d2c6c89f9&plugin=AMap.Geocoder"></script>
  <script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>

<body>
  <div id="container"></div>
  <div id="panel"></div>
  <div style="z-index:100;position: absolute;margin-left: 80px;margin-top: 20px;">
    <input type="text" id="queryAddress">
    <input type="button" onclick="query()" value="搜索">
  </div>
  <div id="redDiv" style="width: 100%;height: 100%;position: absolute;z-index: -1;display: none;">
    <div id="loginPic" style="display:none; position:absolute;width: 100%;height: 100%; z-index: -1;">
      <div style="position:absolute;width: 100%;height: 100%;opacity: 0.15;background: #b3b3b3;"></div>
      <img src="images/login.gif" style="width: 128px;height: 120px;margin-left:45%;margin-top: 300px;">
    </div>
    <div style="width: 40%;margin-top: 15%;margin-left: 25%;opacity: 0.9;background: #fef3d8;"
      align="center">
      <div style="height: 20px;" align="right">
        <input type="button" value="关闭" class="btn btn-primary btn-s-xs"
          onclick="exitDiv()">
      </div>
      <form id="redForm" method="post" enctype="multipart/form-data">
        <input type="hidden" name="userId" value="$!userId">
        <table style="width: 80%;">
          <tr>
            <td/>
            <td style="width: 70%;">
              <h2 style="margin-left: 10px;">发布红包</h2>
            </td>
          </tr>
          <tr>
            <td align="right">文本地址：</td>
            <td>
              <select id="address" name="address"></select>
          </tr>
          <tr>
            <td style="width: 20%;" align="right">经度：</td>
            <td style="width: 70%;">
              <input type="text" readonly="true" id="longitude" name="longitude">
            </td>
          </tr>
          <tr>
            <td align="right">纬度：</td>
            <td>
              <input type="text" readonly="true" id="latitude" name="latitude">
            </td>
          </tr>
          <tr>
            <td align="right">红包个数：</td>
            <td>
              <input type="number" id="redNum" name="redNum">
            </td>
          </tr>
          <tr>
            <td align="right">红包金额：</td>
            <td>
              <input type="number" id="redAmount" name="redAmount" onkeyup="this.value=this.value.replace(/[^\.\d]/g,'')">
            </td>
          </tr>
          <tr>
            <td align="right">红包领取范围：</td>
            <td>
              <input type="number" id="receiveRange" name="receiveRange" value="100"
                required>
            </td>
          </tr>
          <tr>
            <td align="right">红包领取条件：</td>
            <td>
              <select style="width: 172px;padding: 1px 0;" id="ReceiveRequire"
                name="ReceiveRequire">
                <option selected value='0'>全部可领取</option>
                <option value='1'>仅"男"可领取</option>
                <option value='2'>仅"女"可领取</option>
              </select>
            </td>
          </tr>
          <tr>
            <td align="right">线索：</td>
            <td>
              <div style="float: left;width: 80%;margin-left: 5px;" id="photodiv">
                <div style="float:left;background-image:url('images/timg2.jpg');width: 100px;height: 100px;">
                  <input type="file" id="redClue" name="redClue" style="display: none;"
                    onchange="imgChange(this)">
                  <label for="redClue">
                    <div style="width: 100px;height: 100px;"></div>
                  </label>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td align="right">备注：</td>
            <td>
              <textarea rows="7" style="width: 100%" name="remark"></textarea>
            </td>
          </tr>
          <tr>
            <td align="right">链接地址：</td>
            <td>
              <input type="text" id="redURL" name="redURL">
            </td>
          </tr>
          <tr>
            <td></td>
            <td>
              <input type="button" value="确定" class="btn btn-primary btn-s-xs"
                style="margin-left: 30px;" onclick="formSubmit()">
            </td>
          </tr>
          <tr style="height: 30px;">
          </tr>
        </table>
      </form>
    </div>
  </div>
  <script type="text/javascript">
    var map = new AMap.Map("container", {
      resizeEnable: true
    });

    function query() {
      var address = $("#queryAddress").val();
      AMap.service(["AMap.PlaceSearch"], function () {
        var placeSearch = new AMap.PlaceSearch({ //构造地点查询类
          pageSize: 5,
          pageIndex: 1,
          city: "010", //城市
          map: map,
          panel: "panel"
        });
        //关键字查询
        placeSearch.search(address);
      });
    }

    //为地图注册click事件获取鼠标点击出的经纬度坐标
    var clickEventListener = map.on('click', function (e) {
      lnglatXY = [e.lnglat.getLng(), e.lnglat.getLat()];
      var geocoder = new AMap.Geocoder({
        pageSize: 50,
        radius: 500,
        extensions: "all"
      });
      geocoder.getAddress(lnglatXY, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          var Address = result.regeocode.pois;
          var P = document.getElementById("address");
          while (P.hasChildNodes()) {
            P.removeChild(P.firstChild);
          }
          for (var i = 0; i < Address.length; i++) {
            var optionl = document.createElement("option");
            optionl.innerHTML = Address[i].name;
            optionl.value = Address[i].name;
            P.appendChild(optionl);
          }
        }
      });
      $("#longitude").val(e.lnglat.getLng())
      $("#latitude").val(e.lnglat.getLat())
      $("#redDiv").css("z-index", 1000);
      $("#redDiv").css("display", "block");
    });

    function exitDiv() {
      $("#redDiv").css("z-index", -1);
      $("#redDiv").css("display", "none");
    }
    function formSubmit() {
      if (parseInt($("#redNum").val()) < "1" || $("#redNum").val() == "") {
        alert("红包个数不能为空或小于1")
        $("#redNum").val("");
        return;
      }
      if (parseFloat($("#redAmount").val()) < "0.01" || $("#redAmount").val() == "") {
        alert("红包金额不能为空或小于0.01")
        $("#redAmount").val("");
        return;
      }
      if (parseFloat($("#redAmount").val()) / parseInt($("#redNum").val()) < 0.01) {
        alert("每个人领取的红包最小数不能少于0.01元")
        $("#redAmount").val("");
        return;
      }
      if ($("#redClue").val() == "") {
        alert("红包线索不能为空")
        return;
      }
      if ($("#receiveRange").val() == "" || $("#receiveRange").val() <= 0) {
        alert("可领取距离需大于0");
        return;
      }
      var formData = new FormData($("#redForm")[0]);
      $("#loginPic").css("display", "block");
      $("#loginPic").css("z-index", 1000);
      jQuery.ajax({
        type: "post",
        url: "redAdd.do",
        data: formData,
        contentType: false,
        processData: false,
        cache: false,
        success: function (on) {
          if (on == "0") {
            alert("上传线索图片异常");
          } else if (on == "1") {
            alert("创建红包失败");
          } else if (on == "2") {
            alert("创建订单失败");
          } else if (on == "3") {
            alert("支付异常");
          } else if (on == "4") {
            alert("余额不足");
          } else if (on == "5") {
            alert("发放红包成功");
            $("#redDiv").css("display", "none");
            $("#redDiv").css("z-index", -1);
          } else {
            alert("异常，请检查控制台！");
          }
          $("#loginPic").css("display", "none");
          $("#loginPic").css("z-index", -1);
        }
      })
    }
  </script>
  <script type="text/javascript">
    // 前端只需要给input file绑定这个change事件即可（下面两个方法不需要修改）获取到图片
    function imgChange(ele) {
      var imageUrl = getObjectURL($(ele)[0].files[0]);
      convertImgToBase64(imageUrl, function (base64Img) {

        //base64Img为转好的base64,放在img src直接前台展示(<img src="...." />)
        //alert(base64Img);
        //  $("#base").attr("src",base64Img);
        //
        var parentDiv = $(ele).parent();
        parentDiv.find(".uploadFile").val(base64Img.split(",")[1]);//上传的uploadFile
        parentDiv.css({ "background": "url(" + base64Img + ")no-repeat center center", "width": "80px", "height": "80px", "float": "left", "border": "1px solid #e5e5e5", "overflow": "hidden" });
        //base64转图片不需要base64的前缀data:image/jpg;base64
        //alert(base64Img.split(",")[1]);
      });
      //event.preventDefault();
    }
    //createobjecturl()静态方法创建一个包含了DOMString代表参数对象的URL。该url的声明周期是在该窗口中.也就是说创建浏览器创建了一个代表该图片的Url.
    function getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        //web_kit or chrome
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    }


    //生成图片的base64编码
    function convertImgToBase64(url, callback, outputFormat) {
      //html5 的convas画布
      var canvas = document.createElement('CANVAS');
      var ctx = canvas.getContext('2d');
      var img = new Image;
      img.crossOrigin = 'Anonymous';
      img.onload = function () {
        var width = img.width;
        var height = img.height;
        // 按比例压缩4倍
        //var rate = (width<height ? width/height : height/width)/4;
        //原比例生成画布图片
        var rate = 0.1;
        canvas.width = width * rate;
        canvas.height = height * rate;
        ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate);
        // canvas.toDataURL 返回的是一串Base64编码的URL，当然,浏览器自己肯定支持
        var dataURL = canvas.toDataURL(outputFormat || 'image/png');
        callback.call(this, dataURL);
        canvas = null;
      };
      img.src = url;
    }
  </script>
</body>

</html>